package com.tnt.googlekaptcha;

import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author zhuangxl
 * @description
 * @since 2021-03-04 14:42
 */
@RestController
@RequestMapping("/kaptcha")
@Slf4j
public class KaptchaController {

    @Resource
    private Producer producer;

    @GetMapping("/getImage")
    public String getImage(){

        try {

            String kaptchaText = producer.createText();
            log.info("capText = {} ", kaptchaText);
            BufferedImage bi = producer.createImage(kaptchaText);

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(bi, "jpeg", outputStream);
            String base64Image = "data:image/jpeg;base64," + Base64.encodeBase64String(outputStream.toByteArray());

            //return base64Image;

            return "<img src='"+base64Image+"'/>";

        } catch (IOException e) {
            e.printStackTrace();
        }

        return "";
    }
}
